package com.alibaba.pet.service.impl;

import com.alibaba.basic.exception.BusinessException;
import com.alibaba.basic.service.IBaiduAiAuditService;
import com.alibaba.basic.util.*;
import com.alibaba.order.domain.OrderPetAcquisition;
import com.alibaba.order.mapper.OrderPetAcquisitionMapper;
import com.alibaba.org.domain.Employee;
import com.alibaba.org.domain.Shop;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.org.mapper.ShopMapper;
import com.alibaba.pet.domain.Pet;
import com.alibaba.pet.domain.SearchMasterMsg;
import com.alibaba.pet.domain.SearchMasterMsgAuditLog;
import com.alibaba.pet.mapper.PetMapper;
import com.alibaba.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.alibaba.pet.mapper.SearchMasterMsgMapper;
import com.alibaba.pet.query.SearchMasterMsgQuery;
import com.alibaba.pet.service.ISearchMasterMsgService;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.domain.User;
import com.alibaba.user.mapper.UserMapper;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.poi.hssf.record.NoteRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
@Transactional
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
        @Autowired
        private SearchMasterMsgMapper searchMasterMsgMapper;
        @Autowired
        private UserMapper userMapper;
        @Autowired
        private IBaiduAiAuditService baiduAiAuditService;
        @Autowired
        private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
        @Autowired
        private ShopMapper shopMapper;
        @Autowired
        private EmployeeMapper employeeMapper;
        @Autowired
        private PetMapper petMapper;
        @Autowired
        private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //1.获取登录人id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfo(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());// 哪一个用户发布的寻主息消 登录人信息
        // 添加到数据库
        searchMasterMsgMapper.add(searchMasterMsg);// 自增id
        //2.百度AI智能审核
        // 审核文本
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getName()
                + searchMasterMsg.getCoatColor());
        // 审核图片
        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(searchMasterMsg.getId());
        if (boo1 && boo2){
            //2.1.审核成功
            //a.修改状态：0 - 1
            searchMasterMsg.setState(1);
            //保存审核日志
            log.setState(1);
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.add(log);
            //b1.找到最近的店铺 - 分配店铺【设置到shopId】 - 发送短信给店铺管理员，告诉他去接回宠物
            // 先查询所有的店铺
            List<Shop> shops = shopMapper.findAll();
            // 查找到发布寻主消息人的地址
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            // 调用方法查找到距离最近的店铺
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            // 判断最近的店铺是否为null
            if (nearestShop == null){
                //没有找到店铺 - 放到寻主池
                searchMasterMsg.setState(3);
            }else {
                //d.分配成功：给寻主消息设置店铺Id
                searchMasterMsg.setShopId(nearestShop.getId());
                //e.给店铺管理员发短信或邮件：告诉它你有新的订单，请在2天内接回宠物
                Employee employee = employeeMapper.findById(nearestShop.getAdminId());
                // SmsUtils.sendSms(employee.getPhone(),"你有新的订单要处理，请去"+searchMasterMsg.getAddress()+"接回宠物")
                System.out.println("你有新的订单要处理，请去"+searchMasterMsg.getAddress()+"接回宠物");
            }
            searchMasterMsgMapper.update(searchMasterMsg);
        }else {  //3.2.审核失败
            // 修改状态
            searchMasterMsg.setState(-1);
            // 保存到数据库
            searchMasterMsgMapper.update(searchMasterMsg);
            // 保存审核日志
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);
            // 删除寻主用户id
            searchMasterMsgMapper.delete(searchMasterMsg.getId());

            //a.发送短信给用户告诉他审核失败，修改寻主消息
           //  SmsUtils.sendSms(user.getPhone(),"发布寻主失败，请重新发布");
            System.out.println("发布寻主失败，请重新发布");
           return AjaxResult.me().setSuccess(false).setMessage("寻主消息发送失败！！！");

        }
        return new AjaxResult();
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
            // 获取用户id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfo(logininfo.getId());
        // 分页查询
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandel(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 查询待处理的消息
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
       Employee employee =  employeeMapper.findByLogininfoId(logininfo.getId());
       // 分页查询
        query.setShopId(employee.getShopId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> poll(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 查询寻主池的消息
        query.setState(3);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee =  employeeMapper.findByLogininfoId(logininfo.getId());
        // 分页查询
        query.setShopId(employee.getShopId());

        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 查询已完成的消息
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee =  employeeMapper.findByLogininfoId(logininfo.getId());
        // 分页查询
        query.setShopId(employee.getShopId());
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(Map<String, String> map) {
        Long  msgId = Long.parseLong(map.get("msgId"));
        Long empId = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        // 一。校验 当前的待处理寻主消息订单是否处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.findByMsgId(msgId);
        if (order !=null){
            throw new BusinessException("当前的订单正在处理，请勿重复提交");
        }
        // 二。生产pet对象 通过寻主消息对象
        SearchMasterMsg msg = searchMasterMsgMapper.findById(msgId);
        Pet pet = msg2pet(msg);
        petMapper.add(pet);

        // 三。生成收购订单
        OrderPetAcquisition orderTemp = buildOrder(msg,pet,empId,note);
        orderPetAcquisitionMapper.add(orderTemp);

        // 四。通过处理人去接宠物
        Employee employee = employeeMapper.findById(empId);
        SmsUtils.sendSms(employee.getPhone(),"你有新的订单需要处理，请在" + msg.getAddress() +"接回宠物");


    }

    private OrderPetAcquisition buildOrder(SearchMasterMsg msg, Pet pet, Long empId, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        // 生成订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getId()));
        order.setDigest(note);
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        order.setPrice(msg.getPrice());
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet msg2pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setShopId(msg.getShopId());
        // 领养人 - 宠物还没有被领养，所以没有
        // pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return  pet;
    }
}
